-
Decide which of the following conditions are true or false:
-
Decide what each of these C program snippets would do:
-
Write me C conditions for the following:
(3)
(4 - 4)
(4 & 2)
int i = 1, j = 2 ;
if ( i &< j )
{
/* would we get here?? */
}
int i = 1, j = 2 ;
if ( i = j )
{
/* would we get here?? */
}
int i = 0 ;
if ( i++ )
{
/* would we get here?? */
}
int trigger = 0,
command = 0x01;
if((!trigger)
&& ( command & 0x10))
{
/* would we get here?? */
}
I want a condition which is true when j is equal to 10
I want a condition which is true when i is not zero and when j is greater than 7
I want a condition which is true when j is greater than or equal to 5 or bit 3 of mask is set
Answers
-
(3) - TRUE [C reckons any non-zero value is equal to TRUE]
(4-4) - FALSE [Because this expression evaluates to 0, C regards it as FALSE]
(4 & 2) - FALSE [To work out the answer to this one we must first apply the '&' 'arithmetic' operator to the patterns 0010 (2) and 0100 (4). When we do this, we see that none of the bits are set, so the result is 0, which is regarded as FALSE] -
int i = 1, j = 2 ;
if ( i &> j )
{
/* would we get here?? */
}
The condition is true if i is greater than j, and in this case it is not, so the condition would not be entered
int i = 1, j = 2 ;
if ( i = j )
{
/* would we get here?? */
}
This is a nasty one. The '=' operator means assign not compare. This means that the value of i would be copied into j, and the condition would test the value in i. Since this is non-zero, the condition would be entered. Note that this is one of the most common mistakes made by beginning C programmers, If you want to compare i and j make sure to use the '==' operator.
int i = 0 ;
if ( i++ )
{
/* would we get here?? */
}
i starts with value 0, as the ++ operator is applied after the value of i is supplied, the test would not enter the if condition
int trigger = 0,
command = 0x01;
if((!trigger)
&& ( command & 0x10))
{
/* would we get here?? */
}
This is confusing because we are doing a number of different things. We are using the value trigger and putting a '!' in front of it, which means 'not'. Since trigger is 0 and we are 'notting' it, we end up with a non-zero value. This means the logical value of the left side of the '&&' is true. Now we can consider the other side, which must also be true. If we convert the value in command to binary, we get 0001, and if we convert 0x10 to binary, we get 1000 (16 in decimal). If we and these together, we get 0, so that this half of the '&&' condition is 0, so the condition would not be entered.
-
- ( j == 10 ) [Do not put ( j = 10 ) as this is an assignment
- (i != 0 ) && ( j >7 ) [Note I could have put (( (i) && (j>7), but I prefer the more explicit version
- (( j >= 5) || ( mask & 8 )) [Bit 3 is the 'two to power 3' bit, giving a value of 8. If the bit is set we have a non-zero value which we can use on the right side of the expression